package org.game.module.itembo;

import java.util.List;
import java.util.Map;

import com.sojoys.artifact.tools.ToolError;
import org.error.GameErrorCode;
import org.game.constant.SessionConstent;
import org.game.db.bean.Hero;
import org.game.db.bean.Item;
import org.game.db.bean.Player;
import org.game.db.bean.Role;
import org.game.db.cache.ItemCache;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.manager.ItemManager;
import org.game.module.EnterGameHandler;
import org.game.msgBuilder.ItemMsgBuilder;
import org.game.protobuf.c2s.C2SItemMsg.ItemInfo;
import org.game.protobuf.c2s.C2SItemMsg.UseItem;
import org.game.protobuf.s2c.S2CItemMsg.ItemList;
import org.game.protobuf.s2c.S2CItemMsg.UseItemResult;
import org.game.protobuf.s2c.S2CShareMsg.ChangeType;
import org.game.protobuf.s2c.S2CShareMsg.RewardsMsg;
import org.game.util.ProtoUnit;

import com.google.common.collect.Maps;
import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.session.ISession;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * @author : DengYing
 * @CreateDate : 2017年8月21日 上午11:29:13
 * @Description ：Please describe this document
 */
public class ItemBOImpl implements ItemBO,EnterGameHandler {
	@Override
	public void enterGame(Player player) {
	}

	@Override
	public byte[] getItems(ISession session) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		List<Item> items = player.getItemsFkPlayerId();
		ItemList itemList = ItemMsgBuilder.createItemList(ChangeType.DEFAULT, items);
		return ProtoUnit.toByte(itemList);
	}

	@Override
	public byte[] useGoods(ISession session, UseItem param) throws AbstractLogicModelException {
		
		Player player = session.getAttr(SessionConstent.PLAYER);

		
		Hero hero = null;
		if (StrUtil.isNotBlank(param.getHeroId())) {
			hero = player.getPlayerProxy().getHerosByDbId().get(param.getHeroId());
		}
		
		Role role = null;
		if (StrUtil.isNotBlank(param.getRoleId())) {
			role = player.getPlayerProxy().getRoles().get(param.getHeroId());
		}
		
		Map<Long, Integer> goods = Maps.newHashMap();
		for (ItemInfo itemInfo : param.getItemsList()) {
			long dbId = Long.valueOf(itemInfo.getItemId());
			ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR,"根据id没有找到item",ItemCache.me().getById(dbId) == null);
			goods.put(dbId, itemInfo.getNum());
		}
		
		LogDsp log = LogDsp.newBuilder(GoodsDsp.USE_GOODS).addAttr("forGoods", goods.toString());
		
		List<RewardsMsg> rewards = ItemManager.useGoodsByDbId(player, hero, role, goods, param.getCustomParameList(), log);
		
		return ProtoUnit.toByte(UseItemResult.newBuilder().addAllItems(rewards).build());
	}
}
